package com.cykj.faceledtv.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author jzh
 * @date 2019/02/20 16:11
 */
public class IpUtils {
    public static byte[] getIpToByte() {
        try {
            ArrayList<NetworkInterface> niList = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : niList) {
                ArrayList<InetAddress> iaList = Collections.list(ni.getInetAddresses());
                for (InetAddress address : iaList) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
                        return stringIpToByte(address.getHostAddress());
                    }
                }

            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return new byte[]{0, 0, 0, 0};
    }

    public static byte[] stringIpToByte(String ip) {
        String[] ips = ip.split("\\.");
        byte[] result = new byte[4];
        result[0] = (byte) Integer.parseInt(ips[0]);
        result[1] = (byte) Integer.parseInt(ips[1]);
        result[2] = (byte) Integer.parseInt(ips[2]);
        result[3] = (byte) Integer.parseInt(ips[3]);
        return result;
    }

    public static String getIp() {
        try {
            ArrayList<NetworkInterface> niList = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : niList) {
                ArrayList<InetAddress> iaList = Collections.list(ni.getInetAddresses());
                for (InetAddress address : iaList) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) {
                        return address.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return "";
    }
}
